package com.wsoft.bpm.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.wsoft.bpm.vo.AvgApprovalTimeVO;
import com.wsoft.core.exception.Asserts;
import com.wsoft.core.service.CommonAccountService;
import com.wsoft.core.service.CommonMemberService;
import com.wsoft.core.vo.AccountVO;
import com.wsoft.core.vo.MemberVO;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.HistoryService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.task.TaskInfo;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 定时任务记录用户的平均审批时长
 *
 * @author zhonglj
 * @date 2024/12/23 10:39
 **/
@Slf4j
@Service
public class AvgApprovalTimeJob implements Job {
    @Resource
    private HistoryService historyService;
    @Resource
    private CommonMemberService memberService;
    @Resource
    private CommonAccountService accountService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        List<HistoricTaskInstance> allFinishedTask = historyService.createHistoricTaskInstanceQuery()
                .finished()
                .list();

        List<AvgApprovalTimeVO> collect = allFinishedTask.stream()
                .collect(Collectors.groupingBy(TaskInfo::getAssignee))
                .entrySet()
                .stream()
                .map(e -> {
                    AvgApprovalTimeVO avgApprovalTimeVO = new AvgApprovalTimeVO().setAssignee(e.getKey());
                    List<HistoricTaskInstance> tasks = e.getValue();
                    Long avgDuration = 0L;
                    // 统计每个人的单次审批时长
                    if (CollUtil.isNotEmpty(tasks)) {
                        long durations = tasks.stream().mapToLong(HistoricTaskInstance::getDurationInMillis).sum();
                        int times = tasks.size();
                        avgApprovalTimeVO.setAvgExecutionDuration(durations / times);
                    }

                    return avgApprovalTimeVO;
                }).collect(Collectors.toList());

        if (CollUtil.isNotEmpty(collect)) {
            StringBuilder builder = new StringBuilder();
            String template = "用户:【{}】,姓名:【{}】,平均审批时长为:{}";
            Map<Long, MemberVO> memberVOMap = memberService.getMemberList().stream()
                    .collect(Collectors.toMap(MemberVO::getId, e -> e));
            Map<Long, AccountVO> accountVOMap = accountService.getAccountList().stream()
                    .collect(Collectors.toMap(AccountVO::getId, e -> e));
            for (AvgApprovalTimeVO vo : collect) {
                MemberVO memberVO = memberVOMap.get(vo.getAssignee());
                AccountVO accountVO = accountVOMap.get(memberVO.getAccountId());
                builder.append(StrUtil.format(template, accountVO.getLoginName(), memberVO.getName(), DateUtil.formatBetween(vo.getAvgExecutionDuration())))
                        .append("\n");
            }

            Asserts.fail(builder.toString());
        }

    }
}
